<?php
//mq测试
namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Illuminate\Support\Facades\DB;
class MqRecive extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mq:recive';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'mq:recive';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $this->channel = $this->connection->channel();
        $this->channel->exchange_declare('logs','fanout',false,false,false);
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        echo '<pre>';
        //自动生成队列 序号  （队列多个 绑定 要执行的前端 ）
        list($queue_name) = $this->channel->queue_declare("", false, false, true, false);
        $this->channel->queue_bind($queue_name, 'logs');
        //print_r($channel->queue_bind($queue_name, 'logs'));

        echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";

        $callback = function($msg)use($queue_name){
            echo 1;
            echo $queue_name;
            echo ' [x] ', $msg->body, "\n";
        };

        $this->channel->basic_consume($queue_name, '', false, true, false, false, $callback);

        while(count($this->channel->callbacks)) {
            $this->channel->wait();
        }

        $this->channel->close();
        $this->connection->close();
    }
}
